<script setup lang="ts">
  import {
    getDept,
    getDeptDetail,
    editDept,
    delectDept,
    getorgList,
    getOrgAll,
  } from '@/api/syssetting';
  import {
    findIdByKey,
    replaceZeroWithEmpty,
    transformDeptTree,
    transformDeptTreeSelect,
    transformUserData,
  } from '@/utils/utils';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/useLoading';
  import { Message, Modal } from '@arco-design/web-vue';
  import { omit } from 'lodash';
  import Add from './add/index.vue';

  const userStore = useUserStore();
  const visible = ref(false);
  defineOptions({ name: 'departmentSetting' });
  const { loading, setLoading } = useLoading(false);
  const defaultKeys = ref(['0-0-0']);
  const currentKeys = ref();
  setLoading(true);
  const treeData = ref();
  const treeData1 = ref();
  const formType = ref();
  const currentCompany = ref();
  const selectKeys = ref([]);
  const jigoulist = ref();
  function getDeptList() {
    getDept({
      page_on: 1,
      page_size: 1000,
      dept_org_id: currentCompany.value,
    })
      .then((res) => {
        setLoading(true);
        treeData.value = transformDeptTree(res.data.list, '0-0', 'dept_id');
        treeData1.value = transformDeptTreeSelect(
          res.data.list,
          'dept_id',
          'dept_id'
        );
        currentKeys.value = treeData?.value[0]?.id;
        getDetail();
        formType.value = [
          {
            name: 'dept_id',
            label: '部门ID',
            type: 'a-input',
            fieldProps: {
              disabled: true,
              span: 12,
            },
          },
          {
            name: 'dept_name',
            label: '部门名称',
            type: 'a-input',
            fieldProps: {
              span: 12,
            },
            rules: [
              {
                message: '请输入',
                required: true,
              },
            ],
          },
          {
            name: 'dept_leader_id',
            label: '主管领导',
            type: 'a-select',
            fieldProps: {
              span: 12,
              allowSearch: true,
              fieldNames: { value: 'user_id', label: 'user_name' },
            },
            selectOptions: userStore.allUserInfo,
          },
          {
            name: 'dept_competent_id',
            label: '部门主管',
            type: 'a-select',
            fieldProps: {
              span: 12,
              fieldNames: { value: 'user_id', label: 'user_name' },
              allowSearch: true,
            },
            selectOptions: userStore.allUserInfo,
          },
          {
            name: 'dept_contact',
            label: '电话号码',
            type: 'a-input',
            fieldProps: {
              span: 12,
            },
          },
          {
            name: 'dept_parent_id',
            label: '父级机构',
            type: 'a-tree-select',
            fieldProps: {
              span: 12,
              data: treeData1.value ? treeData1.value : [],
            },
          },
          {
            name: 'dept_sort',
            label: '排序号',
            type: 'a-input',
            fieldProps: {
              span: 12,
            },
          },
        ];
      })
      .finally(() => {
        setLoading(false);
      });
  }
  onMounted(() => {
    getOrgAll().then((res: any) => {
      jigoulist.value = res.data;
      getDeptList();
    });
  });
  const formData = ref();
  function getDetail() {
    if (currentKeys.value) {
      getDeptDetail({
        dept_id: currentKeys.value,
      }).then((res) => {
        formData.value = replaceZeroWithEmpty(res.data);
      });
    }
  }

  // 方法定义调整
  function handleNodeSelect(event: Event, data: any) {
    currentKeys.value = data.node.id; // 存储第一个选中节点的key
    getDetail(); // 触发获取详情
  }

  function handleSubmit(form: any) {
    const id = findIdByKey(treeData.value, form.dept_parent_id);
    form.dept_parent_id = id;
    editDept(
      omit(form, [
        'dept_org_name',
        'dept_parent_name',
        'dept_leader_name',
        'dept_competent_id_name',
      ])
    ).then((res) => {
      getDeptList();
      Message.success(res.msg);
    });
  }
  function findIdsByKeys(treeData: any, selectedKeys: any) {
    const result = [];

    function traverse(nodes) {
      nodes.forEach((node) => {
        if (selectedKeys.includes(node.key)) {
          result.push(node.id);
        }
        if (node.children && node.children.length) {
          traverse(node.children);
        }
      });
    }

    traverse(treeData);
    return result;
  }
  function delectAll() {
    if (selectKeys.value.length === 0) {
      Message.warning('请选择部门');
      return false;
    }
    const matchedIds = findIdsByKeys(treeData.value, selectKeys.value);

    Modal.confirm({
      title: '系统提示',
      content: '确定要删除选中的部门吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          delectDept({
            dept_ids: matchedIds,
          })
            .then((res) => {
              if (res?.code == 200) {
                loading.value = true;
                getDeptList();
                selectKeys.value = [];
                Message.success(res?.msg);
                resolve(true);
              } else {
                reject();
              }
            })
            .catch(() => {
              Message.error('删除失败');
              reject();
            });
        });
      },
    });
  }

  function changeSelect(e: any) {
    currentCompany.value = e;
    getDeptList();
  }
</script>

<template>
  <div class="container">
    <a-row gutter="10">
      <a-col span="5">
        <a-card title="部门列表">
          <a-select
            v-model="currentCompany"
            placeholder="请选择机构"
            :options="jigoulist"
            :field-names="{ value: 'org_id', label: 'org_name' }"
            @change="changeSelect"
          >
            <template #prefix> 当前机构 </template>
          </a-select>
          <div style="display: flex; align-items: center; margin-top: 10px">
            <a-spin
              style="
                margin: 0 auto;
                margin-top: 20px;
                min-height: 50px;
                justify-content: center;
              "
              v-if="loading"
              dot
            />
            <a-tree
              v-else
              default-expand-all
              blockNode
              :checkable="true"
              :default-selected-keys="defaultKeys"
              :data="treeData"
              v-model:checked-keys="selectKeys"
              @select="handleNodeSelect"
              :check-strictly="true"
            />
          </div>
          <template #extra>
            <div
              style="display: flex; flex-direction: row; align-items: center"
            >
              <a-tooltip content="删除">
                <div
                  style="cursor: pointer; margin-right: 10px"
                  @click="delectAll"
                >
                  <icon-delete style="color: red" />
                </div>
              </a-tooltip>
              <a-tooltip content="添加">
                <div
                  style="cursor: pointer"
                  @click="
                    () => {
                      visible = true;
                    }
                  "
                >
                  <icon-plus-circle-fill />
                </div>
              </a-tooltip>
            </div>
          </template>
        </a-card>
      </a-col>
      <a-col span="17">
        <a-card title="部门信息" hoverable>
          <div class="formContent" style="display: flex">
            <a-spin
              style="
                margin: 0 auto;
                margin-top: 20px;
                min-height: 50px;
                justify-content: center;
              "
              v-if="loading"
              dot
            />
            <pro-form
              v-if="!loading && currentKeys"
              :btnTitle="['修改']"
              :form-json="formType"
              :form-data="formData"
              @search="handleSubmit"
            ></pro-form>
            <a-empty v-if="!loading && !currentKeys" />
          </div>
        </a-card>
      </a-col>
    </a-row>
    <a-modal>
      <add
        :currentorg="currentCompany"
        v-if="visible"
        v-model:visible="visible"
        :formType="formType"
        :currentKey="currentKeys"
        @refresh="
          () => {
            getDeptList();
            defaultKeys = ['0-0-0'];
          }
        "
      />
    </a-modal>
  </div>
</template>

<style scoped lang="less">
  .container {
    height: 100%;
    background: #f2f3f5;
  }

  .formContent {
    width: 100%;
  }
  // tree的css样式
  :deep(.icon) {
    width: 1.2em !important;
    height: 1.2em !important;
  }

  :deep(.arco-tree-node-title-text) {
    font-size: 12px;
    width: 140px;
    overflow: hidden; /* 隐藏溢出内容 */
    white-space: nowrap; /* 禁止换行 */
    text-overflow: ellipsis; /* 显示省略号 */
  }

  :deep(.arco-tree-node-indent-block) {
    width: 0px !important;
  }

  :deep(.arco-tree-node-indent) {
  }
</style>
